/*
 * vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker:
 *
 * regex.c
 *
 * C.C.Allison
 * chris.allison@hotmail.com
 *
 * Started: Saturday 10 November 2012, 21:33:35
 * Version: 0.00
 * Revision: $Id: regex.c 27 2013-01-09 02:13:28Z chris.charles.allison@gmail.com $
 * Last Modified: Friday 28 December 2012, 22:35:04
 */

#include "regex.h"

char *get_regerror(int errcode, regex_t *compiled)/* {{{1 */
{
    size_t length = regerror (errcode, compiled, NULL, 0);
    char *buffer = malloc (length);
    if(buffer){
        (void) regerror (errcode, compiled, buffer, length);
    }else{
        printf("cannot allocate memory for error buffer\n");
    }
    return buffer;
}/* }}} */
regex_t *init_regex(char *findme)/* {{{1 */
{
    regex_t *compiled;
    char *buf;
    int ret;

    compiled=(regex_t *) malloc(sizeof(regex_t));
    if(compiled){
        ret=regcomp(compiled,findme,REG_EXTENDED);
        if(ret!=0){
            buf=get_regerror(ret,compiled);
            syslog(LOG_ERR,"%s",buf);
            free(compiled);
            compiled=NULL;
        }
    }else{
        CCAC("Failed to allocate memory for regex %s",findme);
    }
    return compiled;
}/* }}} */
void free_regex(regex_t *compiled)/* {{{1 */
{
    if(compiled){
        DBGL("freeing compiled %p\n",compiled);
        regfree(compiled);
        free(compiled);
    }
}/* }}} */
regoff_t do_regex(regex_t *compiled, char *findin)/* {{{1 */
{
    /*
     * returns the byte position in the line of the match
     */
    size_t nummatches=2;
    regmatch_t pmatch[nummatches];
    int ret;
    regoff_t matchpos;

    ret=regexec(compiled, findin,nummatches,pmatch,0);
    if(ret==0){
        matchpos=pmatch[1].rm_so;
    }else{
        matchpos=-1;
    }
    return matchpos;
}/* }}} */
